package com.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.Constants;
import com.example.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-11-26
 * Time: 17:31
 */

//封装的非常NB~~~~~~~~~
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    //注入Bean对象
    @Autowired
    private CaptchaProperties captchaProperties;

    //会话合理的超时时间单位ms毫秒
    private final static long session_valid_timeout = 60 * 1000;
    //把图片写入到响应流中，我们的get方法就直接返回void就行了
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {
//定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //设置一下response的内容，太单调了
        response.setContentType("image/jpeg");
        //禁止缓存:固定格式
        response.setHeader("Progma","No-cache");


//图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        //以用户为基本单位，创建session对象存储，Code,避免多线程安全问题
        session.setAttribute(captchaProperties.getSession().getKey(),lineCaptcha.getCode());
        //记录一下建立session时的时间戳
        session.setAttribute(captchaProperties.getSession().getData(),new Date());
        response.getOutputStream().close();//关闭流，节省资源
    }

    @RequestMapping("check")
    public Boolean check(String inputCode , HttpSession session){
        //判断inputCode是否有值
        if(!StringUtils.hasLength(inputCode)){
            return false;
        }
        //拿到Code(服务器生成的验证码值)
        String saveCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        //拿到时间戳
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getData());
        //对服务器和用户生成的验证码进行校验
        if(inputCode.equalsIgnoreCase(saveCode)){//忽略大小写
            //判断验证码是否过期
            //先判断saveDate为不为null
            if(saveDate != null && System.currentTimeMillis()-saveDate.getTime() < session_valid_timeout){
                return true;
            }
        }
        return false;

    }
}
